import React, { memo } from 'react'

import type { ReactNode } from 'react'
import { CategoryWrapper } from './style'
import { useAppSelector } from '@/store'
import { useDispatch } from 'react-redux'
import { fetchChangeCategoryAction } from '../../store/songs'
import { useNavigate } from 'react-router-dom'

interface IProps {
  children?: ReactNode
}

const SongsCategory: React.FC<IProps> = () => {
  const { FirstCategory } = useAppSelector((state) => ({
    FirstCategory: state.songs.FirstCategory
  }))
  const dispatch = useDispatch()
  const navigate = useNavigate()
  function selectCategory(name: string) {
    dispatch<any>(fetchChangeCategoryAction(name))
    if (name == '全部') {
      navigate(`/discover/songs`)
    } else {
      navigate(`/discover/songs/?cat=${name}`)
    }
}
    /* 另一种写法 */
/*     const [searchParams, setSearchParams] = useSearchParams()
    function selectCategory(name: string) {
    dispatch<any>(fetchChangeCategoryAction(name))
    setSearchParams({ cat: name })
  } */

  return (
    <CategoryWrapper>
      <div className="arrow sprite_icon"></div>
      <div className="all">
        <a onClick={() => selectCategory('全部')}>全部风格</a>
      </div>
      <div className="category">
        {Object.entries(FirstCategory.categories).map(([key, value]) => {
          return (
            <dl key={key} className={'item' + key}>
              <dt>
                <i className="icon sprite_icon2"></i>
                <a>{String(value)}</a>
              </dt>
              <dd>
                {FirstCategory.sub
                  .filter((sItem: any) => sItem.category === Number(key))
                  .map((sItem: any) => {
                    return (
                      <div className="item" key={sItem.name}>
                        <a onClick={() => selectCategory(sItem.name)}>
                          {sItem.name}
                        </a>
                        <span className="divider">|</span>
                      </div>
                    )
                  })}
              </dd>
            </dl>
          )
        })}
      </div>
    </CategoryWrapper>
  )
}

export default memo(SongsCategory)
